#include "sendudp.h"
#include "../udp/udp_maker.h"
#include "../ip/ip_maker.h"
uint8_t *make_complete_pck(int fd, uint16_t id, uint8_t *mac, uint8_t *source_ip_address,
                           uint8_t *target_ip_address);

int main()
{
    char tap_name[] = "tap1";
    int fd = open_tap(tap_name);
    if (fd == -1)
    {
        ERR("can not open tap name %s", tap_name);
        perror(strerror(errno));
        exit(errno);
    }
    int flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1)
    {
        ERR("get tap fd sys flags err %s %d", strerror(errno), errno);
        exit(errno);
    };
    int err = fcntl(fd, F_SETFL, flags | O_NONBLOCK);
    if (err == -1)
    {
        ERR("set tap fd nonblock flags err %s %d", strerror(errno), errno);
        exit(errno);
    }
    uint8_t source_hw_address[] = {0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f};
    uint8_t source_ip_address[] = {192, 168, 2, 252};
    uint8_t target_ip_address[] = {192, 168, 2, 156};
    uint16_t loop_count = 0;
    uint8_t *mac = mac_get(fd, target_ip_address, source_ip_address, source_hw_address);
    while (1)
    {
        sleep(1);
        uint8_t *complete_pck = make_complete_pck(fd, loop_count, mac,source_ip_address,target_ip_address);
        __write_all(fd, complete_pck, 14 + 20 + 38);
        free(complete_pck);
        loop_count += 1;
    }
}

uint8_t *make_complete_pck(int fd, uint16_t id, uint8_t *mac, uint8_t *source_ip_address,

                           uint8_t *target_ip_address)
{
    uint8_t source_hw_address[] = {0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f};

    struct ether_header mac_header;
    int mac_header_len = sizeof(struct ether_header);
    // need free

    LOG("set mac header");
    memcpy(mac_header.ether_shost, source_hw_address, 6);
    memcpy(mac_header.ether_dhost, mac, 6);
    mac_header.ether_type = htons(0x0800);
    print_arr((&mac_header), mac_header_len, 'x');
    uint8_t udp_data[30] = {0};
    // need free
    LOG("set udp header");
    uint8_t *udp_head = udp_maker(8080, 8080, 38, udp_data, 30, source_ip_address, target_ip_address);
    print_arr(udp_head, 38, 'x');
    // need free
    LOG("set ip header");
    uint8_t *ip_head = ip_maker(38, id, source_ip_address, target_ip_address);
    print_arr(ip_head, 20, 'd');
    // need free
    LOG("make complete pck");
    uint8_t *complete_pck = malloc(mac_header_len + 20 + 38);
    memcpy(complete_pck, &mac_header, mac_header_len);
    memcpy(complete_pck + mac_header_len, ip_head, 20);
    memcpy(complete_pck + mac_header_len + 20, udp_head, 8);
    memcpy(complete_pck + mac_header_len + 20 + 8, udp_data, 30);
    free(udp_head);
    free(ip_head);
    print_arr(complete_pck, mac_header_len + 20 + 38, 'x');
    return complete_pck;
}